const vmPicture = weex.requireModule('vmPicture')

const Image = Object.create(null)

Image.install = (Vue, options) => {
  Vue.prototype.$picture = {
    camera({ ratioX = 0, ratioY = 0, cropWidth = 0, cropHeight = 0, allowCrop = false, base64 = false }) {
      return new Promise((resolve, reject) => {
        vmPicture.camera({
          ratioX,
          ratioY,
          cropWidth,
          cropHeight,
          allowCrop,
          base64
        }, ({ status, errorMsg, data }) => {
          status === 0 ? resolve(data) : reject({ status, errorMsg, data })
        })
      })
    },
    pick({ maxCount = 9, ratioX = 0, ratioY = 0, cropWidth = 0, cropHeight = 0, allowCrop = false, base64 = false }) {
      return new Promise((resolve, reject) => {
        vmPicture.pick({
          maxCount,
          ratioX,
          ratioY,
          cropWidth,
          cropHeight,
          allowCrop,
          base64
        }, ({ status, errorMsg, data }) => {
          status === 0 ? resolve(data) : reject({ status, errorMsg, data })
        })
      })
    },
    qrcode({ url, width = 400, height = 400, prefix = true }) {
      return new Promise((resolve, reject) => {
        if (!url) {
          reject({
            stauts: 9,
            errorMsg: '没有要生成二维码的内容',
            data: null
          })
        }
        vmPicture.qrcode({
          url,
          width,
          height
        }, ({ status, errorMsg, data }) => {
          status === 0 ? resolve(`${prefix ? 'data:image/png;base64,' : ''}${data}`) : reject({ status, errorMsg, data })
        })
      })
    },
    video({second = 15, type = 'both', tip = '', quality = 8}) {
      return new Promise((resolve, reject) => {
        vmPicture.video({
          second, // 没有作用
          type,   // 录制模式：拍照 capture，录相 recorder， 两者都有（默认）both
          tip,    // 提示文字
          quality // 视频质量 1~20，数字越大，质量越高
        }, ({ status, errorMsg, data }) => {
          // 通过data的长度判断录制模式
          if (status === 0 && data && data.length) {
            resolve({ type: data.length === 1 ? 'capture' : 'recorder', data })
          } else {
            reject({ status, errorMsg, data })
          }
        })
      })
    },
    videoPreview({url = '' }) {
      return new Promise((resolve, reject) => {
        if (!url) {
          reject('没有视频地址')
        }
        vmPicture.videoPreview({
          url,
        }, ({ status, errorMsg, data }) => {
          status === 0 ? resolve(data) : reject({ status, errorMsg, data })
        })
      })
    },
  }
}

Vue.use(Image)
